package com.robot.controller;

import com.robot.common.api.CurrentUserSupport;
import com.robot.common.enums.ActionUnitTypeEnum;
import com.robot.common.enums.RoleCodeEnum;
import com.robot.common.result.PageResult;
import com.robot.common.result.Response;
import com.robot.dao.cache.ActionUnitTemplateCache;
import com.robot.dao.dto.*;
import com.robot.dao.entity.ActionUnitTemplate;
import com.robot.dao.entity.RobotUserUsetime;
import com.robot.dao.entity.User;
import com.robot.dao.mapper.UserMapper;
import com.robot.dao.vo.ActionUnitTemplateVO;
import com.robot.dao.vo.AgentDetailVO;
import com.robot.dao.vo.FileSetOverViewVO;
import com.robot.service.RobotService;
import com.robot.service.RobotUserUsetimeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/robot")
@Slf4j
@Api(tags = "机器人相关接口")
public class RobotController {

    @Autowired
    private RobotService robotService;
    @Autowired
    private CurrentUserSupport currentUserSupport;
    @Autowired
    private RobotUserUsetimeService robotUserUsetimeService;
    @Qualifier("userMapper")
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/queryByIdAndCategory")
    @ApiOperation("根据用户ID和类目ID分页查询机器人列表")
    public Response<PageResult> pageQueryRobotByCategoryId(@RequestBody RobotPageQueryDTO robotPageQueryDTO) {
        if (robotPageQueryDTO.getUserId()==null || robotPageQueryDTO.getUserId().equals("")) {
            robotPageQueryDTO.setUserId(String.valueOf(currentUserSupport.getCurrentUserId()));
        }

        PageResult pageResult = robotService.queryRobotList(robotPageQueryDTO);
        return Response.success(pageResult);
    }


    @PostMapping("/queryByUserId")
    @ApiOperation(value = "根据用户ID查询机器人")
    public Response<PageResult> queryByUserId(@RequestBody RobotPageQueryDTO robotPageQueryDTO) {
        if (robotPageQueryDTO.getUserId()==null || robotPageQueryDTO.getUserId().equals("")) {
            robotPageQueryDTO.setUserId(String.valueOf(currentUserSupport.getCurrentUserId()));
        }
        PageResult pageResult = robotService.queryByUserId(robotPageQueryDTO);

        return Response.success(pageResult);
    }

    @PostMapping("/create/template")
    @ApiOperation(value = "根据模板创建机器人")
    public Response<AgentDetailVO> createByTemplate(@RequestBody IDDTO iddto) {
        if (iddto.getUserId()==null || iddto.getUserId().equals("")) {
            iddto.setUserId(String.valueOf(currentUserSupport.getCurrentUserId()));
        }
        AgentDetailVO agentDetailVO = robotService.createByTemplate(iddto);

        return Response.success(agentDetailVO);
    }

    @PostMapping("/detail")
    @ApiOperation(value = "查询机器人详细信息")
    public Response<AgentDetailVO> queryRobotDetailByRobotId(@RequestBody QueryRobotDetailDTO queryRobotDetailDTO) {
        AgentDetailVO agentDetailVO = robotService.queryRobotIdByRobotId(queryRobotDetailDTO);
        //todo 判断用户权限用户权限
        agentDetailVO.setRoleCode(RoleCodeEnum.NORMAL_USER.getCode());
        return Response.success(agentDetailVO);
    }

    @PostMapping("/top")
    @ApiOperation(value = "置顶机器人")
    public Response top(@RequestBody IDDTO iddto) {

        robotUserUsetimeService.creatrobotuser(iddto.getRobotId(),iddto.getUserId());
        return Response.success();
    }

    @PostMapping("/untop")
    @ApiOperation(value = "取消置顶机器人")
    public Response untop(@RequestBody IDDTO iddto) {
        robotUserUsetimeService.deleterobotuser(iddto.getRobotId(),iddto.getUserId());
        return Response.success();
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除机器人（逻辑删除）")
    public Response delete(@RequestBody IDDTO iddto) {
        robotUserUsetimeService.deleterobot(iddto.getRobotId());
        robotService.delete(iddto);
        return Response.success();
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改机器人信息")
    public Response update(@RequestBody AgentDTO agentDTO) {
        robotService.updateRobotDetail(agentDTO);
        return Response.success();
    }

    @PostMapping("/create/sentence")
    @ApiOperation(value = "一句话新建机器人")
    public Response<AgentDetailVO> createBySentence(@RequestBody CreateRobotDTO createRobotDTO) {
        AgentDetailVO agentDetailVO = null;
        try {
            agentDetailVO = robotService.createBySentence(createRobotDTO);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Response.success(agentDetailVO);
    }

    @PostMapping("/create/files")
    @ApiOperation(value = "上传文件新建机器人")
    public Response<AgentDetailVO> createByUploadFiles(@RequestBody CreateRobotDTO createRobotDTO) {
        AgentDetailVO agentDetailVO = null;
        try {
            agentDetailVO = robotService.createByUploadFiles(createRobotDTO);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return Response.success(agentDetailVO);
    }

    @PostMapping("/queryTemplateList")
    @ApiOperation("组件模板列表查询")
    public Response<List<ActionUnitTemplateVO>> queryActionUnitTemplate(@RequestBody ActionUnitTemplageDTO actionUnitTemplageDTO) {
        List<ActionUnitTemplateVO> response = new ArrayList<>();
        for (Integer i : actionUnitTemplageDTO.getActionUnitTypeList()) {
            List<ActionUnitTemplate> actionUnitTemplate = new ArrayList<>();
            for (ActionUnitTemplate value : ActionUnitTemplateCache.cache.values()) {
                if (Objects.equals(value.getActionUnitType(), i)) {
                    if (Objects.equals(i, ActionUnitTypeEnum.BIG_MODEL.getCode())) {
                        if (Objects.equals(value.getUnitTemplateCode(), "ai_big_model_robot")) {
                            RobotPageQueryDTO robotPageQueryDTO = new RobotPageQueryDTO();
                            robotPageQueryDTO.setPage(1);
                            // todo 往前端传的其他智能体数量是写死的，和产品沟通下（0902晚没联系上产品
                            robotPageQueryDTO.setPageSize(5);

                            robotPageQueryDTO.setUserId(String.valueOf(currentUserSupport.getCurrentUserId()));
                            robotPageQueryDTO.setCategoryName(null);//为null时查询全部类别
                            List records = robotService.queryRobotList(robotPageQueryDTO).getRecords();
//                            JSONArray jsonArray = JSONArray.parseArray(records.toString());
//                            System.out.println(records);
                            value.setExtraInfo(records);
                            actionUnitTemplate.add(value);
                            continue;
//                        for (Object record : records) {
//                            record.
//                        }
//                        System.out.println(records);
                        }
                    }
                    actionUnitTemplate.add(value);


                }
            }
            ActionUnitTemplateVO actionUnitTemplateVO = new ActionUnitTemplateVO();
            actionUnitTemplateVO.setActionUnitTemplate(actionUnitTemplate);
            response.add(actionUnitTemplateVO);
        }
//        System.out.println(response);
        return Response.success(response);

    }

    @PostMapping("/actionUnit/createFileSet")
    @ApiOperation("新建数据源组件")
    public Response<FileSetOverViewVO> createFileSetActionUnit(@RequestBody FileSetDTO fileSetDTO) {
        FileSetOverViewVO fileSetOverViewVO = robotService.createFileSetActionUnit(fileSetDTO);
        return Response.success(fileSetOverViewVO);
    }

    @PostMapping("/noviceGuide")
    @ApiOperation(value = "新手引导")
    public Response robotnoviceGuide(@RequestBody NoviceGuideDTO noviceGuideDTO) throws IOException {
        noviceGuideDTO.setUserId(currentUserSupport.getCurrentUserId());
        User user = new User();
        user.setId(noviceGuideDTO.getUserId());
        User usertmp = userMapper.queryById(user);
        List<Long> robotId;
        for (String categoryname : noviceGuideDTO.getCategorys()) {
            robotService.topCategoryName(categoryname,usertmp.getCompanyCode(), String.valueOf(noviceGuideDTO.getUserId()));
        }
        return Response.success();
    }

    @PostMapping("/queryleftsidebar")
    public Response<PageResult> queryleftsidebar(@RequestBody RobotPageQueryDTO robotPageQueryDTO) {
        robotPageQueryDTO.setUserId(String.valueOf(currentUserSupport.getCurrentUserId()));
        PageResult pageResult=robotUserUsetimeService.pagequerybyuserid(robotPageQueryDTO.getUserId(), robotPageQueryDTO.getPage(), robotPageQueryDTO.getPageSize());
        return Response.success(pageResult);
    }
}
